<?php

namespace app\api\controller;

use ba\Tree;
use Throwable;
use com\tyme\solar\SolarDay;
use com\tyme\holiday\LegalHoliday;
use think\facade\Db;
use think\facade\Config;
use app\common\model\User;
use app\common\controller\Frontend;
use EasyWeChat\MiniApp\Application;
use think\facade\Log;
use app\common\model\SubscribeOrder;
use app\admin\model\SubscribeRecord;
class Subscribe extends Frontend{

    protected array $noNeedLogin = ['index','times','inspect','gdlist','goods','config','record'];
    protected array $noNeedPermission = ['buy','vip','order','my','detail','qrcode','add'];

    public function initialize(): void
    {
        parent::initialize();
        
    }
    public function add(){
        if($this->request->isPost()){
            $id = $this->request->post('id',0);
            $order = SubscribeRecord::where('id',$id)->find();
            if($order['state'] > 3){
                $this->error('邀约已结束');
            }
            $record = SubscribeRecord::where('order_id',$id)->where('user_id',$this->auth->id)->find();
            if(empty($record)){//查验重复
                $subscribeRecode = SubscribeRecord::where('order_id',$id)->where('subscribe_type',1)->withoutField('create_time,update_time')->select();
                $insertRecode = [];
                foreach ($subscribeRecode as $key => $value) {
                            $subRecode = $value->toArray();
                            $subRecode['user_id'] = $this->auth->id;
                            $subRecode['subscribe_type'] = 2;
                            unset($subRecode['id']);
                        $insertRecode[]=$subRecode;  

                }
                $subrcord = new SubscribeRecord();
                $subrcord->saveAll($insertRecode);
                $this->success('加入对局成功',null,200);
            }else{
                $this->error('不能重复参与');
            }
        }
    }

    public function record(){
        if($this->request->isPost()){
            $id = $this->request->post('id',0);
            $user_id = SubscribeRecord::where('order_id',$id)->column('user_id');
            $user = Db::name('User')->where('id','in',$user_id)->select();
            $this->success('',$user,200);
        }
    }
    public function my(){
        if($this->request->isPost()){
            $page = $this->request->post('page',1);
            $list = SubscribeRecord::withJoin('stadium','left')->where('subscribe_record.user_id',$this->auth->id)->where('subscribe_record.status',1)->page($page,10)->order('id desc')->select();
            $this->success('',$list,200);
        }
    }

    public function detail(){
        if($this->request->isPost()){
            $id = $this->request->post('id',0);
           $order =  SubscribeRecord::withJoin('stadium','left')->where('subscribe_record.status',1)->where('subscribe_record.id',$id)->find();
           $isopen = get_sys_config('is_open');
           if($isopen == 0 && $order->state==2){
            $order->state=3;
            $order->save();
           }
           $this->success('',$order,200);
        }
    }

    public function qrcode(){
        if($this->request->isPost()){
            $id = $this->request->post('id',0);
            $order =  SubscribeRecord::where('status',1)->where('id',$id)->find();
            if($order['state'] > 3 && (time()-$order['update_time']) > 300 ){
                $this->error('已核销');
            }
            $text = 'S'.$order['id'].'U'.$order['user_id'];
            $this->success('',$text,200);
        }
    }
    /**
     * 排期
     */
    public function times(){
        $week=[
            0=>'周日',
            1=>'周一',
            2=>'周二',
            3=>'周三',
            4=>'周四',
            5=>'周五',
            6=>'周六',

        ];
        $timeZone = new \DateTime();
        $timeZone->setTime(0,0);
        $maxTimestamp = mktime(0, 0, 0, date('m')+2, date('d')-1, date('Y'));
        $timeStep = true;
        $list = [];
        do {
            $timestamp = $timeZone->getTimestamp();
            $timeFormatString = $timeZone->format('Y-m-d');
            $timeString = $timeZone->format('n.d');
            $weekstring = $week[$timeZone->format('w')];
            if($timestamp >= $maxTimestamp){
                $timeStep =false;
            }
            $list[]=[
                'name'=>$timeString,
                'week'=>$weekstring,
                'value'=>$timeFormatString
            ];
            $timeZone->modify('+1 day');
            # code...
        } while ($timeStep);
        $this->success('',$list,200);
    }
    /**
     * 预约场地
     */
    public function index(){
        $day = $this->request->param('day');
        $daytimestamp = strtotime($day);
        $workday = false;
        $times = get_sys_config('ordinary_times'); //默认开放时段；
        //$holidays_verify = get_sys_config('holidays_verify'); //节假日检测
        $charg_cost = get_sys_config('charg_cost');
        if(get_sys_config('holidays_verify') == 1){
            $holiday = LegalHoliday::fromYmd(date('Y',$daytimestamp), date('m',$daytimestamp), date('d',$daytimestamp));
            $workday = $holiday->isWork();
        }
        if($workday){
            $times = get_sys_config('holidays_times'); //节假日开放时段；
        }
        $stadium = Db::name('Stadium')->where('status',1)->order('weigh desc')->select()->toArray();
        $data = [];
        foreach ($stadium as $key => $value) {
            foreach($times as $v){
                $data[$key][] = [
                    'times'=>$v,
                    'stadium_name'=>$value['name'],
                    'stadium'=>$value['id'],
                    'disable'=> Db::name('SubscribeRecord')->where('status',1)->where('state','>','0')->where('year',date('Y',$daytimestamp))
                    ->where('month',date('m',$daytimestamp))->where('days',date('d',$daytimestamp))->where('hour',$v)->where('stadium_id',$value['id'])->find()?1:0,
                ];
            }
        }
        $this->success('',[
            'charg_cost'=>$charg_cost,
            'stadium'=>$stadium,
            'times'=>$times,
            'data'=>$data
        ],200);
    }
    /**
     * 预约检测
     */
    public function inspect (){
        $data = $this->request->param();
        $daytimestamp = strtotime($data['day']);
        $record = Db::name('SubscribeRecord')->where('status',1)->where('state','>','0')->where('year',date('Y',$daytimestamp))
                    ->where('month',date('m',$daytimestamp))->where('days',date('d',$daytimestamp))->where('hour',$data['hour'])->where('stadium_id',$data['stadium_id'])->find();
        if($record != null){
            $this->error('场地已被约');
        }
        $this->success('',null,200);
    }
    /**
     * 商城商品
     */
    public  function gdlist(){
        $goods = $this->customerGoods();
        $this->success('',$goods,200);
    }
    
    public function goods(){
        $id = $this->request->param('id');
        $goods = $this->customerGoods();
        $info = [];
        foreach ($goods as $key => $value) {
            if($value['id'] == $id){
                $info = $value;
            }
        }
        $this->success('',$info,200);
    }
    /**
     * 生成商城预订单
     */
    public function buy(){
        if($this->request->isPost()){
            $data = $this->request->post();
            $data['order_type'] = 0;
            $result = SubscribeOrder::createOrder($data,$this->auth->getUserInfo());
            if($result !== false){
                $this->success('',$result,200);
            }else{
                $this->error('不支持购买');
            }
            
        }
    }
    //普通预约
    
    public function order(){
        if($this->request->isPost()){
            $data = $this->request->post();
            $verify = false;
            foreach($data['record'] as $key=>$value){
                $daytimestamp = strtotime($value['day']);
                $record = Db::name('SubscribeRecord')->where('status',1)->where('state','>','0')->where('year',date('Y',$daytimestamp))
                    ->where('month',date('m',$daytimestamp))->where('days',date('d',$daytimestamp))->where('hour',$value['hour'])->where('stadium_id',$value['stadium_id'])->find();
                if($record != null){
                    $verify =true;
                }
            }
            if($verify){
                $this->error('场地已被约');
            }
            $data['order_type'] = 0;
            $result = SubscribeOrder::subscribe($data,$this->auth->getUserInfo());
            if($result !== false){
                $this->success('',$result,200);
            }else{
                $this->error('不支持购买');
            }
            
        }
    }
    /**
     * 免付款
     */
    public function vip(){
        if($this->request->isPost()){
            $data = $this->request->post();
            $verify = false;
            foreach($data['record'] as $key=>$value){
                $daytimestamp = strtotime($value['day']);
                $record = Db::name('SubscribeRecord')->where('status',1)->where('state','>','0')->where('year',date('Y',$daytimestamp))
                    ->where('month',date('m',$daytimestamp))->where('days',date('d',$daytimestamp))->where('hour',$value['hour'])->where('stadium_id',$value['stadium_id'])->find();
                if($record != null){
                    $verify =true;
                }
            }
            if($verify){
                $this->error('场地已被约');
            }
            $data['order_type'] = 1;
            $result = SubscribeOrder::subscribe($data,$this->auth->getUserInfo());
            if($result !== false){
                $this->success('',$result,200);
            }else{
                $this->error('不支持购买');
            }
            
        }
    }

    protected function customerGoods(){
       $goods = Db::name('SubscribeGoods')->where('status',1)->order('id asc')->column('id,sale_once,config_name as type','id');
       $vip = get_sys_config('vip_card');
       $vip_remark = get_sys_config('vip_remark');
       $detail = [];
       foreach ($goods as $key => $value) {
            $value['image'] = $this->request->domain().'/static/'.$value['id'].'.jpg';
            switch ($value['id']) {
                case '1':
                    $value['price'] = get_sys_config('once_big_cost');
                    $value['content'] = get_sys_config('once_big_remark');
                    $value['title'] = '成人入场券';
                    break;
                case '2':
                    $value['price'] = get_sys_config('once_small_cost');
                    $value['content'] = get_sys_config('once_small_remark');
                    $value['title'] = '青少年入场券';
                    break;
                case '3':
                    $value['price'] = $vip[0]['value'];
                    $value['content'] = $vip_remark;
                    $value['title'] = '至尊VIP月卡';
                    break;
                case '4':
                    $value['price'] = $vip[1]['value'];
                    $value['content'] = $vip_remark;
                    $value['title'] = '至尊VIP季卡';
                    break;
                case '5':
                    $value['price'] = $vip[2]['value'];
                    $value['content'] = $vip_remark;
                    $value['title'] = '至尊VIP年卡';
                    break;  
            }
            $detail[] = $value;
       }
       return $detail;
    }

    public function config(){
        $this->success('',1,200);
    }


}